use crate::db;
use crate::model::user::{CreateUserRequest, UpdateUserRequest, User};

// 根据ID获取用户
pub async fn get_user(id: u64) -> Result<Option<User>, sqlx::Error> {
    sqlx::query_as!(User, "SELECT * FROM user WHERE id = ?", id)
        .fetch_optional(db!())
        .await
}

// 获取所有用户
pub async fn get_all_users() -> Result<Vec<User>, sqlx::Error> {
    sqlx::query_as!(User, "SELECT * FROM user")
        .fetch_all(db!())
        .await
}

// 分页获取用户
pub async fn get_users_by_page(page: i32, page_size: i32) -> Result<Vec<User>, sqlx::Error> {
    sqlx::query_as!(
        User,
        "SELECT * FROM user LIMIT ?, ?",
        (page - 1) * page_size,
        page_size
    )
    .fetch_all(db!())
    .await
    .map(|r| r.into_iter().collect())
}

// 创建用户
pub async fn create_user(request: CreateUserRequest) -> Result<u64, sqlx::Error> {
    sqlx::query!(
        "INSERT INTO user (username, password, nickname, email) VALUES (?, ?, ?, ?)",
        request.username,
        request.password,
        request.nickname,
        request.email
    )
    .execute(db!())
    .await
    .map(|r| r.last_insert_id())
}

// 更新用户
pub async fn update_user(id: u64, request: UpdateUserRequest) -> Result<u64, sqlx::Error> {
    sqlx::query!(
        "UPDATE user SET password = ?, nickname = ?, email = ? WHERE id = ?",
        request.password,
        request.nickname,
        request.email,
        id
    )
    .execute(db!())
    .await
    .map(|r| r.rows_affected())
}

// 删除用户
pub async fn delete_user(id: u64) -> Result<u64, sqlx::Error> {
    sqlx::query!("DELETE FROM user WHERE id = ?", id)
        .execute(db!())
        .await
        .map(|r| r.rows_affected())
}
